package com.winit.openapi.wop.inbound.validator;

import java.util.Date;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.inbound.vo.InboundEnumConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.wop.inbound.constant.InboundParameter.InputInboundCreate;
import com.winit.pms.spi.winit.vo.WinitProduct;

/**
 * 海外仓入库单 校验器类
 * 
 * @version <pre>
 * Author     Version       Date        Changes
 * dinghua.an   1.0         2015年11月10日     Created
 *
 * </pre>
 * @since 1.
 */
public class InboundOrderfieldValidator {

	private final static String EXPORT_DECLARATION_TYPE_SELF = "SelfDeclaration" ;
	

    /**
     * 校验创建海外仓入库单参数保存到草稿
     * 校验字段长度
     * @param json
     */
    public static void validSaveAsDraftField(JSONObject json) {
        ValidateUtil.validMaxLength(json, "orderNo", 64);
        
        ValidateUtil.validMaxLength(json, "orderType", 20);
        
        ValidateUtil.validMaxLength(json, "unitName", 20);
        ValidateUtil.validMaxLength(json, "importerCode", 50);
        
        ValidateUtil.validMaxLength(json, "exporterCode", 50);
        ValidateUtil.validMaxLength(json, "logisticsPlanNo", 50);
        
    }
    
    public static void validUnpickupOrderField(JSONObject json) {
        /*
         * 获取入库方式，根据入库方式，校验不同字段 基本：描述 标准订单：物流，提货验货配置校验 直发国内验：提货验货配置校验 直发海外：无
         */
        ValidateUtil.validMaxLength(json, "desc", 255, false);
        // 入库单
        ValidateUtil.validNotNull(json, "orderNo");
        ValidateUtil.validNotNull(json, "entryWhType");
        String entryWhType = (String) json.get("entryWhType");
        if (InboundEnumConstant.OrderType.STANDARD.getType().equals(entryWhType)) {
            ValidateUtil.validNotNull(json, "logistics");
            JSONObject logisticsJson = json.getJSONObject("logistics");
            if (logisticsJson != null) {
                // 进口商
                ValidateUtil.validMaxLength(json, "importerCode", 20, true);
                // 出口商
                ValidateUtil.validMaxLength(json, "exporterCode", 20, true);
                // 物流计划
                ValidateUtil.validMaxLength(json, "logisticsPlanNo", 50, true);
            }
        }
        if (!InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(entryWhType)) {
            JSONObject dispatchInfoJson = json.getJSONObject("dispatchInfo");
            if (dispatchInfoJson != null) {
                // 验证提货信息
                InboundPickupFieldValidator.validInspectionPickUp(dispatchInfoJson);
            }
        }
    }
    
    /**
     * 
     * 标准海外仓入库单订单参数校验
     * @param order
     */
    public static void validInboundOrder(JSONObject json,WinitProduct winitProduct){
        validInboundOrderField(json,winitProduct);
        InboundPackagefieldValidator.validCreatePackageField(json);
    }
    
    /**
     * 
     * 根据调用模块校验订单信息
     * 1、卖家网站基本信息模块---base
     * 2、卖家网站跨国物流信息模块---logistics
     * 3、API下入库单
     * @param json
     */
    private static void validInboundOrderField(JSONObject json,WinitProduct winitProduct) {
    	
    	//基本信息校验
        ValidateUtil.validNotNull(json, InputInboundCreate.orderType.getName());
        ValidateUtil.validNotNull(json, InputInboundCreate.winitProductCode.getName());
        //客户订单号
		ValidateUtil.validMaxLength(json, InputInboundCreate.sellerOrderNo.getName(),50,false);
		//目的仓
		ValidateUtil.validNotNull(json, InputInboundCreate.destinationWarehouseCode.getName());
		ValidateUtil.validMaxLength(json, InputInboundCreate.destinationWarehouseCode.getName(), 40, true);
        String orderType = json.getString("orderType");
        if (InboundEnumConstant.OrderType.STANDARD.getType().equals(orderType)) {//标准入库
        	if(!"OW0101".equals(winitProduct.getProductCatalogName())){
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        	//验货仓
        	ValidateUtil.validNotNull(json, InputInboundCreate.inspectionWarehouseCode.getName());
        	ValidateUtil.validMaxLength(json, InputInboundCreate.inspectionWarehouseCode.getName(), 40, true);
        	
        	if (org.apache.commons.lang3.StringUtils.isNotEmpty(json.getString(InputInboundCreate.importDeclarationRuleCode.getName()))) {
        	    // 如果有规则，则走的升级
        	    ValidateUtil.validMaxLength(json, InputInboundCreate.importDeclarationRuleCode.getName(), 50, true);
        	    
            	//出口报关类型编码
                ValidateUtil.validNotNull(json, InputInboundCreate.exportDeclarationType.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.exportDeclarationType.getName(), 50, true);
        	} else {
        	    // 适配
        	    //进口商编码
                ValidateUtil.validNotNull(json, InputInboundCreate.importerCode.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.importerCode.getName(), 40, true);
                //出口商编码
                ValidateUtil.validNotNull(json, InputInboundCreate.exporterCode.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.exporterCode.getName(), 40, true);
        	}
        	
        	//物流单号
        	ValidateUtil.validNotNull(json, InputInboundCreate.logisticsPlanNo.getName());
        	ValidateUtil.validMaxLength(json, InputInboundCreate.logisticsPlanNo.getName(), 40, true);
        	//校验提货验货\信息
        	ValidateUtil.validNotNull(json, "dispatchInfo", "dispatchInfo");
        	InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
        }else if (InboundEnumConstant.OrderType.DIRECT_INNER.getType().equals(orderType)){//直发国内
        	if(!"OW0102".equals(winitProduct.getProductCatalogName())){
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        	if("Y".equals(winitProduct.getIsSelfInspection())){//自验
        		if("Y".equals(winitProduct.getIsContainTransnationalTransportSu())){//Winit承运
        		    if (org.apache.commons.lang3.StringUtils.isNotEmpty(json.getString(InputInboundCreate.importDeclarationRuleCode.getName()))) {
                        // 如果有规则，则走的升级
                        ValidateUtil.validMaxLength(json, InputInboundCreate.importDeclarationRuleCode.getName(), 50, true);
                        
                        //出口报关类型编码
                        ValidateUtil.validNotNull(json, InputInboundCreate.exportDeclarationType.getName());
                        ValidateUtil.validMaxLength(json, InputInboundCreate.exportDeclarationType.getName(), 50, true);
                    } else {
                        //进口商编码
                        ValidateUtil.validNotNull(json, InputInboundCreate.importerCode.getName());
                        ValidateUtil.validMaxLength(json, InputInboundCreate.importerCode.getName(), 40, true);
                        
                        //校验出口报关信息
                        validateExporterInfoForDirectOrder(json);
                    }
                	
                	//物流单号
                	ValidateUtil.validNotNull(json, InputInboundCreate.logisticsPlanNo.getName());
                	ValidateUtil.validMaxLength(json, InputInboundCreate.logisticsPlanNo.getName(), 40, true);
        			//校验送港信息
                	ValidateSendPortInfo(json);
        		}else{//直发
        			ValidateDirectForecastInfo(json);
        		}
        	}else{//非自验
        		//验货仓
        		ValidateUtil.validNotNull(json, InputInboundCreate.inspectionWarehouseCode.getName());
        		ValidateUtil.validMaxLength(json, InputInboundCreate.inspectionWarehouseCode.getName(), 40, true);
        		//校验提货验货\信息
        		ValidateUtil.validNotNull(json, "dispatchInfo", "dispatchInfo");
        		InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
        		ValidateDirectForecastInfo(json);
        	}
        }else if (InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(orderType)){
        	if(!"OW0103".equals(winitProduct.getProductCatalogName())){
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        	if("Y".equals(winitProduct.getIsContainTransnationalTransportSu())){//Winit承运
        	    if (org.apache.commons.lang3.StringUtils.isNotEmpty(json.getString(InputInboundCreate.importDeclarationRuleCode.getName()))) {
                    // 如果有规则，则走的升级
                    ValidateUtil.validMaxLength(json, InputInboundCreate.importDeclarationRuleCode.getName(), 50, true);
                    
                    //出口报关类型编码
                    ValidateUtil.validNotNull(json, InputInboundCreate.exportDeclarationType.getName());
                    ValidateUtil.validMaxLength(json, InputInboundCreate.exportDeclarationType.getName(), 50, true);
                } else {
                    //进口商编码
                    ValidateUtil.validNotNull(json, InputInboundCreate.importerCode.getName());
                    ValidateUtil.validMaxLength(json, InputInboundCreate.importerCode.getName(), 40, true);
                    //校验出口报关信息
                    validateExporterInfoForDirectOrder(json);
                }
        		
            	//物流单号
            	ValidateUtil.validNotNull(json, InputInboundCreate.logisticsPlanNo.getName());
            	ValidateUtil.validMaxLength(json, InputInboundCreate.logisticsPlanNo.getName(), 40, true);
            	//校验送港信息
            	ValidateSendPortInfo(json);
    		}else{//直发
    			ValidateDirectForecastInfo(json);
    		}
        }else if (InboundEnumConstant.OrderType.STORAGE_INBOUND.getType().equals(orderType)){
        	if(!"SSW11".equals(winitProduct.getProductCatalogName())){
        		System.out.println("ss");
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        	//验货仓
        	ValidateUtil.validNotNull(json, InputInboundCreate.inspectionWarehouseCode.getName());
        	ValidateUtil.validMaxLength(json, InputInboundCreate.inspectionWarehouseCode.getName(), 40, true);
        	
        	if (org.apache.commons.lang3.StringUtils.isNotEmpty(json.getString(InputInboundCreate.importDeclarationRuleCode.getName()))) {
                // 如果有规则，则走的升级
                ValidateUtil.validMaxLength(json, InputInboundCreate.importDeclarationRuleCode.getName(), 50, true);
                
                //出口报关类型编码
                ValidateUtil.validNotNull(json, InputInboundCreate.exportDeclarationType.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.exportDeclarationType.getName(), 50, true);
            } else {
                // 适配
                //进口商编码
                ValidateUtil.validNotNull(json, InputInboundCreate.importerCode.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.importerCode.getName(), 40, true);
                //出口商编码
                ValidateUtil.validNotNull(json, InputInboundCreate.exporterCode.getName());
                ValidateUtil.validMaxLength(json, InputInboundCreate.exporterCode.getName(), 40, true);
            }
        	//物流单号
        	ValidateUtil.validNotNull(json, InputInboundCreate.logisticsPlanNo.getName());
        	ValidateUtil.validMaxLength(json, InputInboundCreate.logisticsPlanNo.getName(), 40, true);
        	//校验提货验货\信息
        	ValidateUtil.validNotNull(json, "dispatchInfo", "dispatchInfo");
        	InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
        }else if (InboundEnumConstant.OrderType.STORAGE_DIRECT_INNER.getType().equals(orderType)){
        	if(!"SSW12".equals(winitProduct.getProductCatalogName())){
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        	if("Y".equals(winitProduct.getIsSelfInspection())){//自验
        		if("Y".equals(winitProduct.getIsContainTransnationalTransportSu())){//Winit承运
        		    if (org.apache.commons.lang3.StringUtils.isNotEmpty(json.getString(InputInboundCreate.importDeclarationRuleCode.getName()))) {
                        // 如果有规则，则走的升级
                        ValidateUtil.validMaxLength(json, InputInboundCreate.importDeclarationRuleCode.getName(), 50, true);
                        
                        //出口报关类型编码
                        ValidateUtil.validNotNull(json, InputInboundCreate.exportDeclarationType.getName());
                        ValidateUtil.validMaxLength(json, InputInboundCreate.exportDeclarationType.getName(), 50, true);
                    } else {
                        //进口商编码
                        ValidateUtil.validNotNull(json, InputInboundCreate.importerCode.getName());
                        ValidateUtil.validMaxLength(json, InputInboundCreate.importerCode.getName(), 40, true);
                        //校验出口报关信息
                        validateExporterInfoForDirectOrder(json);
                    }
        			
                	//物流单号
                	ValidateUtil.validNotNull(json, InputInboundCreate.logisticsPlanNo.getName());
                	ValidateUtil.validMaxLength(json, InputInboundCreate.logisticsPlanNo.getName(), 40, true);
        			//校验送港信息
                	ValidateSendPortInfo(json);
        		}else{//直发
        			ValidateDirectForecastInfo(json);
        		}
        	}else{
        		throw new ApiException("产品编码与订单类型不匹配!");
        	}
        }
        else{
        	throw new ApiException("不支持的订单类型!");
        }
         /**********API下单，所有入参校验****************************/
         //validateInboundOrderByType(json);
    }
    
    /**
     * 校验直发单出口报关信息（直发国内、直发海外、直发存储仓）
     * @param json
     */
    private static void validateExporterInfoForDirectOrder(JSONObject json) {
    	String exportDeclarationType = null;//出口报关类型
    	if(json.containsKey(InputInboundCreate.exportDeclarationType.getName())){
    		exportDeclarationType = json.getString(InputInboundCreate.exportDeclarationType.getName());
    	}
    	//出口商编码为空时，校验是否为“自报关”
    	if(!json.containsKey(InputInboundCreate.exporterCode.getName()) 
    			|| StringUtils.isEmpty(json.getString(InputInboundCreate.exporterCode.getName()) )){
    		if(!EXPORT_DECLARATION_TYPE_SELF.equals(exportDeclarationType)){
    			throw new ApiException(ErrorCode.UN_SELF_DECLARATION_NEED_EXPORTER_CODE,InputInboundCreate.exportDeclarationType.getName(),InputInboundCreate.exporterCode.getName());
    		}
    	}
    	//“自报关”时，不允许填写出口商编码
    	else if(EXPORT_DECLARATION_TYPE_SELF.equals(exportDeclarationType)){
    		if(json.containsKey(InputInboundCreate.exporterCode.getName()) 
        			&& !StringUtils.isEmpty(json.getString(InputInboundCreate.exporterCode.getName()) )){
    			throw new ApiException(ErrorCode.SELF_DECLARATION_NOT_EXPORTER_CODE,InputInboundCreate.exportDeclarationType.getName(),InputInboundCreate.exporterCode.getName());
        	}
		}else{
			ValidateUtil.validNotNull(json, InputInboundCreate.exporterCode.getName());
        	ValidateUtil.validMaxLength(json, InputInboundCreate.exporterCode.getName(), 40, true);
		}
		
	}

	/**
     * 校验送港信息
     * @param json
     */
    private static void ValidateSendPortInfo(JSONObject json) {
    	ValidateUtil.validNotNull(json, "sendPortInfo", "sendPortInfo");
    	JSONObject sendPortInfoJson = json.getJSONObject("sendPortInfo");
    	ValidateUtil.validNotNull(sendPortInfoJson, InputInboundCreate.sendPortType.getName());
    	String sendPortType = sendPortInfoJson.getString(InputInboundCreate.sendPortType.getName());
    	if("WINIT".equals(sendPortType)){//Winit送港
    		ValidateUtil.validNotNull(sendPortInfoJson, InputInboundCreate.pickupCartonAddressCode.getName());
    	}else if("SELF".equals(sendPortType)){//自送港
    		ValidateUtil.validNotNull(sendPortInfoJson, InputInboundCreate.sendPortDate.getName());
    		ValidateUtil.validDateString(sendPortInfoJson, InputInboundCreate.sendPortDate.getName(), DateUtil.SIMPLE_DATE_STRING);
    		Date now = new Date();
            Date sendPortDate = DateUtil.parse2Date(sendPortInfoJson.getString(InputInboundCreate.sendPortDate.getName()), DateUtil.SIMPLE_DATE_STRING);
            if(!now.before(sendPortDate)){
                throw new ApiException(ErrorCode.START_AFTER_END,"Now",InputInboundCreate.sendPortDate.getName());
            }
    		ValidateUtil.validMaxLength(sendPortInfoJson, InputInboundCreate.sendPortInfo_containerNo.getName(), 50, false);
    		ValidateUtil.validMaxLength(sendPortInfoJson, InputInboundCreate.sendPortInfo_sealNo.getName(), 50, false);
    	}else{
    		throw new ApiException(ErrorCode.FIELD_ERROR,InputInboundCreate.sendPortType.getName());
    	}
		
	}

	private static void ValidateDirectForecastInfo(JSONObject json) {
    	final String DATE_FORMAT = "yyyy-MM-dd";
		ValidateUtil.validNotNull(json, "directForecastInfo", "directForecastInfo");
		JSONObject directForecastInfoJson = json.getJSONObject("directForecastInfo");
    	ValidateUtil.validNotNull(directForecastInfoJson, InputInboundCreate.preparedOffPortDate.getName());
    	ValidateUtil.validDateString(directForecastInfoJson, InputInboundCreate.preparedOffPortDate.getName(),DATE_FORMAT);
    	ValidateUtil.validNotNull(directForecastInfoJson, InputInboundCreate.preparedArrivePortDate.getName());
    	ValidateUtil.validDateString(directForecastInfoJson, InputInboundCreate.preparedArrivePortDate.getName(),DATE_FORMAT);
    	ValidateUtil.validDateBefore(directForecastInfoJson, InputInboundCreate.preparedOffPortDate.getName(), InputInboundCreate.preparedArrivePortDate.getName());
    	Date now = new Date();
        Date offPortDate = DateUtil.parse2Date(directForecastInfoJson.getString(InputInboundCreate.preparedOffPortDate.getName()), DateUtil.SIMPLE_DATE_STRING);
        if(!now.before(offPortDate)){
            throw new ApiException(ErrorCode.START_AFTER_END,"NOW",InputInboundCreate.preparedOffPortDate.getName());
        }
	}

	/**
     * 
     * 根据订单类型校验:
     * 1、基本信息：winit产品、验货仓、目的仓、卖家订单号
     * 2、跨国物流信息：进出口商、物流计划
     * 3、提货/验货信息：验货方式、提货类型、发货供应商编码/名称、快递单号
     * @param json
     */
    private static void validateInboundOrderByType(JSONObject json){
        String orderType = json.getString("orderType");
        if(InboundEnumConstant.OrderType.STANDARD.getType().equals(orderType)){
            //基本信息
            ValidateUtil.validMaxLength(json, "warehouseCode", 40, true);//验货仓
            ValidateUtil.validMaxLength(json, "destinationWarehouseCode", 40, true);//目的仓
            ValidateUtil.validMaxLength(json, "productCode", 40, true);//产品编码
            ValidateUtil.validMaxLength(json, "customerOrderNo", 255);//客户订单号
            //物流信息
            ValidateUtil.validMaxLength(json, "importerCode", 20, true);// 进口商
            //ValidateUtil.validInteger(json, "importerCode", true);//整型
            ValidateUtil.validMaxLength(json, "exporterCode", 20, true);// 出口商
            ValidateUtil.validInteger(json, "exporterCode", true);//整型
            ValidateUtil.validMaxLength(json, "logisticsPlanNo", 50, true);// 物流计划
            //提货验货信息
            ValidateUtil.validNotNull(json, "dispatchInfo");
            InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
            
        } else if (InboundEnumConstant.OrderType.DIRECT_INNER.getType().equals(orderType)){
            //直发国内验  没有跨国物流信息
            ValidateUtil.validMaxLength(json, "warehouseCode", 40, true);//验货仓
            
            ValidateUtil.validNotNull(json, "dispatchInfo");
            InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
        } else if (InboundEnumConstant.OrderType.DIRECT_WH.getType().equals(orderType)){
            //直发海外验   没有跨国物流、提货信息
        } else if (InboundEnumConstant.OrderType.LOCATION_INBOUND.getType().equals(orderType)) {
            //本地仓入库  没有跨国物流信息
            ValidateUtil.validMaxLength(json, "warehouseCode", 40, true);//验货仓
            
            ValidateUtil.validNotNull(json, "dispatchInfo");
            InboundPickupFieldValidator.validInspectionPickUp(json.getJSONObject("dispatchInfo"));
        } else {
            throw new ApiException("不支持的订单类型!");
        }
        ValidateUtil.validMaxLength(json, "productCode", 32, true);// winit产品
        ValidateUtil.validMaxLength(json, "destinationWarehouseCode", 40, true);//目的仓
        ValidateUtil.validMaxLength(json, "customerOrderNo", 255);// 客户订单号
        
    }
}
